﻿using APP.QUANLY.Common;
using eService.BLL;
using HLVControl.Grid.Data;
using MetroUI.Forms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace eService.Presentation
{
    public partial class frmNhapKho : MetroForm
    {
        ExcuteNHACUNGCAP exeNCC = new ExcuteNHACUNGCAP();
        ExcuteNHOMHANG exeNhomHang = new ExcuteNHOMHANG();
        ExcuteKHO exeKho = new ExcuteKHO();
        ExcuteDONVI exeDonVi = new ExcuteDONVI();
        ExcuteHANGHOA exeMatHang = new ExcuteHANGHOA();
        ExecuteNHAPKHO exe = new ExecuteNHAPKHO();

        public frmNhapKho()
        {
            InitializeComponent();
            LoadAll();
        }

        private void LoadAll()
        {

            LoadData();
            LoadUI();
        }

        private void LoadUI()
        {
            LoadMacDinhUI();
            labMaPhieu.Text = TaoMaPhieu(true);
            LoadHoaDon(labMaPhieu.Text);
        }

        public void LoadData()
        {
            LoadToCmbKho();
            LoadToCmbNhaCungCap();
            LoadToPnlNhomHang();
            LoadDSMatHang(0);
            LoadThongTinMatHang(null);
        }

        private void LoadToCmbNhaCungCap()
        {
            try
            {

                List<PARTNERINFO> list = exeNCC.GetAll();
                DataTable data = new DataTable();
                data.Columns.Add("Mã", typeof(int));
                data.Columns.Add("Nhà cung cấp", typeof(string));
                foreach (PARTNERINFO obj in list)
                {
                    data.Rows.Add(obj.PartnerID, obj.Name);
                }
                cmbNhaCungCap.DataSource = data;
                cmbNhaCungCap.DisplayMember = "Nhà cung cấp";
                cmbNhaCungCap.ValueMember = "Mã";
                cmbNhaCungCap.ColumnWidths = "0,200";
                cmbNhaCungCap.SelectedIndex = -1;
                cmbNhaCungCap.Text = "";
            }
            catch
            {

            }
        }
        private void LoadToCmbKho()
        {
            try
            {

                List<WAREHOUSE> list = exeKho.GetAll();
                DataTable data = new DataTable();
                data.Columns.Add("Mã", typeof(string));
                data.Columns.Add("Kho hàng", typeof(string));
                foreach (WAREHOUSE obj in list)
                {
                    data.Rows.Add(obj.WHID, obj.WHNamw);
                }
                cmbKho.DataSource = data;
                cmbKho.DisplayMember = "Kho hàng";
                cmbKho.ValueMember = "Mã";
                cmbKho.ColumnWidths = "0,200";
                cmbKho.SelectedIndex = -1;
                cmbKho.Text = "";
            }
            catch
            {

            }
        }
        private void LoadToPnlNhomHang()
        {
            try
            {
                List<GROUPPRODUCT> list = exeNhomHang.GetAll();

                if (list == null) return;
                if (list.Count == 0) return;

                Screen scr = Screen.PrimaryScreen;
                int vitrix = 0;
                int vitriy = 5;
                int khoangcach = 10;
                int TinhKhoangCach = khoangcach * list.Count;
                int ChieuRong = (scr.WorkingArea.Width - 700 - TinhKhoangCach) / (list.Count + 1);
                int ChieuDai = pnlNhomHang.Height - 10;
                List<PRODUCT> listP = new List<PRODUCT>();
                listP = exeMatHang.GetAll().Where(c => c.IsUse == true).ToList();
                if (listP == null) return;

                //-----------------------------------
                Button btnTatCa = new Button();
                btnTatCa.BringToFront();
                btnTatCa.BackColor = Color.FromArgb(128, 255, 128);
                btnTatCa.FlatStyle = FlatStyle.Flat;
                btnTatCa.FlatAppearance.BorderColor = Color.FromArgb(51, 51, 51);
                btnTatCa.FlatAppearance.BorderSize = 1;
                btnTatCa.FlatAppearance.MouseDownBackColor = Color.FromArgb(128, 255, 128);
                btnTatCa.FlatAppearance.MouseOverBackColor = Color.FromArgb(128, 255, 128);
                btnTatCa.Font = new Font("Segoe UI", (float)8.75, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                btnTatCa.UseVisualStyleBackColor = false;
                btnTatCa.ForeColor = Color.FromArgb(51, 51, 51);
                btnTatCa.Height = ChieuDai;
                btnTatCa.Width = ChieuRong;
                btnTatCa.UseVisualStyleBackColor = false;
                btnTatCa.Name = "0";
                btnTatCa.Text = "Tất cả";
                btnTatCa.Tag = "0";

                btnTatCa.Location = new Point(vitrix + khoangcach, vitriy);
                vitrix += ChieuRong + khoangcach;

                pnlNhomHang.Controls.Add(btnTatCa);
                btnTatCa.Click += btnLmh_Click;
                //----------------------------------

                foreach (GROUPPRODUCT obj in list)
                {
                    if (obj.PRODUCTS.Count > 0)
                    {
                        Button btnLmh = new Button();
                        btnLmh.BringToFront();
                        btnLmh.BackColor = Color.White;
                        btnLmh.FlatStyle = FlatStyle.Flat;
                        btnLmh.FlatAppearance.BorderColor = Color.FromArgb(51, 51, 51);
                        btnLmh.FlatAppearance.BorderSize = 1;
                        btnLmh.FlatAppearance.MouseDownBackColor = Color.FromArgb(128, 255, 128);
                        btnLmh.FlatAppearance.MouseOverBackColor = Color.FromArgb(128, 255, 128);
                        btnLmh.Font = new Font("Segoe UI", (float)8.75, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                        btnLmh.UseVisualStyleBackColor = false;
                        btnLmh.ForeColor = Color.FromArgb(51, 51, 51);
                        btnLmh.Height = ChieuDai;
                        btnLmh.Width = ChieuRong;
                        btnLmh.UseVisualStyleBackColor = false;
                        btnLmh.Name = obj.GpID.ToString();
                        btnLmh.Text = obj.GpName;
                        btnLmh.Tag = obj.GpID;

                        btnLmh.Location = new Point(vitrix + khoangcach, vitriy);
                        vitrix += ChieuRong + khoangcach;

                        pnlNhomHang.Controls.Add(btnLmh);
                        btnLmh.Click += btnLmh_Click;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private void LoadMacDinhUI()
        {
            txtNguoiLap.Text = StaticVar.user.FullName;
            dtpNgayNhap.Value = DateTime.Today;
            txtChungTu.Text = "";
            txtDienThoai.Text = "";
            txtDiaChi.Text = "";
            txtGhiChu.Text = "";
            numCongNo.Value = 0;
            labTongTien.Text = "0";
            numTienChi.Value = 0;
            numChietKhau.Value = 0;
            numTienChietKhau.Value = 0;
            numTienKM.Value = 0;
            numThanhToan.Value = 0;
            labMaKho.Text = "";
            labMaNCC.Text = "";
            cmbKho.Text = "";
            cmbNhaCungCap.Text = "";
            labMaNhomHang.Text = "0";
            labMaHang.Text = "";
            labMaPhieu.Text = "";
            labMaChiTiet.Text = "0";
            txtTimKiem.Text = "";
            UIHelper.LoadFocus(txtTimKiem);
        }
        private string TaoMaPhieu(bool isTam)
        {
            string MaPhieu = "";
            try
            {
                if (!isTam)
                {
                    int ThuTu = exe.SoLuongPhieuNhap();
                    if (ThuTu == 0) MaPhieu = "NK0001";
                    else MaPhieu = "NK" + (ThuTu + 1).ToString("D4");
                }
                else
                {
                    MaPhieu = Guid.NewGuid().ToString();
                }
            }
            catch { }
            return MaPhieu;
        }
        void btnLmh_Click(object sender, EventArgs e)
        {
            try
            {
                Button btn = (Button)sender;
                foreach (Button b in pnlNhomHang.Controls)
                {
                    b.BackColor = Color.White;
                }

                btn.BackColor = Color.FromArgb(128, 255, 128);
                labMaNhomHang.Text = btn.Name;
                int MaNhom = int.Parse(labMaNhomHang.Text);
                LoadDSMatHang(MaNhom);
            }
            catch { }
        }
        private void btnThoat_Click(object sender, EventArgs e)
        {
            if (treeHoaDon.Rows.Count > 0)
            {
                if (MessageBox.Show("Phiếu nhập này chưa được tạo.\nBạn có chắc muốn thoát không?", "Thông Báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    XoaPhieuTam(true);
                }
                else return;
            }
            this.Close();
        }

        private void LoadHoaDon(string MaHoaDon)
        {
            try
            {
                treeHoaDon.Rows.Clear();
                DataTable data = exe.HoaDon(MaHoaDon);
                if (data != null && data.Rows.Count > 0)
                {
                    int count = 1;
                    foreach (DataRow drow in data.Rows)
                    {
                        TreeListRow row = treeHoaDon.CreateRow();
                        row.Cells.Add(new TreeListCell(count));
                        row.Cells.Add(new TreeListCell(drow[0].ToString()));
                        row.Cells.Add(new TreeListCell(drow[1].ToString()));
                        row.Cells.Add(new TreeListCell(drow[2].ToString()));
                        row.Cells.Add(new TreeListCell(drow[3].ToString()));
                        row.Cells.Add(new TreeListCell(drow[4].ToString()));
                        row.Cells.Add(new TreeListCell(drow[5].ToString()));
                        row.Cells.Add(new TreeListCell(string.Format("{0:###,0}",Decimal.Parse(drow[6].ToString()))));
                        row.Cells.Add(new TreeListCell(string.Format("{0:###,0}",Decimal.Parse(drow[7].ToString()))));

                        treeHoaDon.Rows.Add(row);
                        count++;
                    }
                }
                treeHoaDon.Refresh();
                labTongTien.Text = string.Format("{0:###,0}", exe.TongThanhTien(labMaPhieu.Text));
            }
            catch
            { }
        }
        private void LoadDSMatHang(int MaNhom)
        {
            try
            {
                treeDanhMuc.Rows.Clear();
                List<PRODUCT> list = null;

                if (MaNhom != 0) list = exeMatHang.GetAll().Where(c => c.GpID == MaNhom).ToList();
                else list = exeMatHang.GetAll();

                if (list != null && list.Count > 0)
                {
                    int count = 1;
                    foreach (PRODUCT obj in list)
                    {
                        TreeListRow row = treeHoaDon.CreateRow();
                        row.Cells.Add(new TreeListCell(count));
                        row.Cells.Add(new TreeListCell(obj.PrID));
                        row.Cells.Add(new TreeListCell(obj.PrName));

                        UNITPRODUCT objDV = exeDonVi.GetByID(obj.PrUnitID);
                        if (objDV != null) row.Cells.Add(new TreeListCell(objDV.UnitName));
                        else row.Cells.Add(new TreeListCell("--"));

                        row.Cells.Add(new TreeListCell(string.Format("{0:###,0}",obj.PrPriceBase)));

                        treeDanhMuc.Rows.Add(row);
                        count++;
                    }
                }
                treeDanhMuc.Refresh();
                treeDanhMuc.RefreshGrouping();
            }
            catch
            { }
        }
        private void LoadThongTinMatHang(PRODUCT obj)
        {
            if (obj != null)
            {
                txtTenHangDuocChon.Text = obj.PrName;
                labMaHang.Text = obj.PrID.ToString();
                UNITPRODUCT objDV = exeDonVi.GetByID(obj.PrUnitID);
                if (objDV != null) labDonViChon.Text = objDV.UnitName;
                numDonGiaChon.Value = (decimal)obj.PrPriceBase;
            }
            else
            {
                txtTenHangDuocChon.Text = "";
                labMaHang.Text = "";
                labDonViChon.Text = "";
                numDonGiaChon.Value = 0;
                //MessageBox.Show("Vui lòng chọn mặt hàng để nhập vào phiếu!");
            }
        }

        private void XoaPhieuTam(bool isThoat)
        {
            if (labMaPhieu.Text == "")
            {
                MessageBox.Show("Xóa thất bại!");
                return;
            }
            bool KQ = false;
            KQ = exe.XoaPhieuTam();
            if (!isThoat) if (KQ) MessageBox.Show(exe.ErrMsg);
            if (KQ)
            {
                LoadUI();
            }
        }
        private void XoaMatHang()
        {
            if (labMaPhieu.Text == "")
            {
                MessageBox.Show("Xóa thất bại!");
                return;
            }
            if (labMaChiTiet.Text == "")
            {
                MessageBox.Show("Vui lòng chọn mặt hàng trong hóa đơn để xóa!");
                return;
            }
            bool KQ = false;
            try
            {
                TreeListRow firstSelected = treeHoaDon.SelectedElements[0] as TreeListRow;
                int ID = int.Parse(firstSelected.Cells[3].Text);
                PRODUCT obj = exeMatHang.GetByID(ID);
                if (obj == null) return;
                KQ = exe.XoaMatHang(labMaPhieu.Text, obj.PrID);
                if (KQ)
                {
                    MessageBox.Show("Xóa mặt hàng thành công!");
                    LoadHoaDon(labMaPhieu.Text);
                }
                else
                {
                    MessageBox.Show("Xóa mặt hàng thất bại!");
                }
            }
            catch
            {
                MessageBox.Show("Vui lòng chọn mặt hàng cần xóa!");
            }
            
        }

        private void cmbKho_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbKho.SelectedIndex >= 0)
            {
                DataRowView drvData = (DataRowView)cmbKho.SelectedItem;
                string Ma = drvData.Row.ItemArray[0].ToString();
                string Ten = drvData.Row.ItemArray[1].ToString();
                labMaKho.Text = Ma;
                cmbKho.Text = Ten;
            }
        }
        private void cmbNhaCungCap_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbNhaCungCap.SelectedIndex >= 0)
            {
                DataRowView drvData = (DataRowView)cmbNhaCungCap.SelectedItem;
                string Ma = drvData.Row.ItemArray[0].ToString();
                string Ten = drvData.Row.ItemArray[1].ToString();
                PARTNERINFO obj = exeNCC.GetByID(int.Parse(Ma));
                if (obj == null) return;
                labMaNCC.Text = Ma;
                cmbNhaCungCap.Text = Ten;
                txtDienThoai.Text = obj.Phone;
                txtDiaChi.Text = obj.Address;
            }
        }
        private void treeDanhMuc_AfterSelectionChange(object sender, HLVControl.Grid.Events.TreeListElementEventArgs e)
        {
            try
            {
                TreeListRow firstSelected = treeDanhMuc.SelectedElements[0] as TreeListRow;
                int ID = int.Parse(firstSelected.Cells[1].Text);
                PRODUCT obj = exeMatHang.GetByID(ID);
                if (obj == null) return;
                LoadThongTinMatHang(obj);
            }
            catch
            {

            }
        }
        private void btnNhapHang_Click(object sender, EventArgs e)
        {
            try
            {
                if (labMaNCC.Text == "")
                {
                    MessageBox.Show("Vui lòng chọn nhà cung cấp trước khi nhập mặt hàng!");
                    return;
                }
                if (labMaKho.Text == "")
                {
                    MessageBox.Show("Vui lòng chọn kho trước khi nhập mặt hàng!");
                    return;
                }
                if (labMaHang.Text == "")
                {
                    MessageBox.Show("Vui lòng chọn mặt hàng cần nhập!");
                    return;
                }
                if (numSLNhap.Value <= 0)
                {
                    MessageBox.Show("Số lượng nhập phải lớn hơn không!");
                    return;
                }
                bool KQ = false;
                numSLNhap.Value = numSLNhap.Value + exe.SoLuongHienTai(labMaPhieu.Text, int.Parse(labMaHang.Text));
                KQ = exe.XuLyNghiepVu(labMaPhieu.Text, int.Parse(labMaChiTiet.Text), int.Parse(labMaHang.Text), (int)numSLNhap.Value, (double)numDonGiaChon.Value, int.Parse(labMaNCC.Text), labMaKho.Text, (float)numChietKhau.Value, (double)numTienKM.Value, (double)numTienChi.Value, StaticVar.user.UserName, "Mới tạo", 1, txtGhiChu.Text, false,"","NhapMatHang");
                if (KQ)
                {
                    LoadHoaDon(labMaPhieu.Text);
                    numSLNhap.Value = 1;
                }
            }
            catch
            {

            }
        }

        private void txt_Enter(object sender, EventArgs e)
        {
            UIHelper.txt_Enter(sender, e);
        }
        private void txt_Leave(object sender, EventArgs e)
        {
            UIHelper.txt_Leave(sender, e);
        }
        private void txt_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                //TextBox txt = sender as TextBox;
                //if (txt.Name == txtTen.Name)
                //    UIHelper.txt_KeyPress(sender, numTu0Den8, e);
                //if (txt.Name == numTu0Den8.Name)
                //    UIHelper.txt_KeyPress(sender, numTu8Den18, e);
                //if (txt.Name == numTu8Den18.Name)
                //    UIHelper.txt_KeyPress(sender, numTu18Den24, e);
                //if (txt.Name == numTu18Den24.Name)
                //    UIHelper.txt_KeyPress(sender, cmbKhuVuc, e);
                //if (txt.Name == cmbKhuVuc.Name)
                //    UIHelper.txt_KeyPress(sender, numSTT, e);
                //if (txt.Name == numSTT.Name)
                //    UIHelper.txt_KeyPress(sender, txtGhiChu, e);
                //if (txt.Name == txtGhiChu.Name)
                //    UIHelper.txt_KeyPress(sender, btnXacNhan, e);
                //if (txt.Name == txtTimKiem.Name)
                //    UIHelper.txt_KeyPress(sender, btnTimKiem, e);
            }
            catch { }
        }
        private void btnTimKiem_Click(object sender, EventArgs e)
        {
            SearchProvider.SmartSearch(treeDanhMuc, txtTimKiem.Text.Trim(), new List<string> { });
        }
        private void num_ValueChanged(object sender, EventArgs e)
        {
            decimal TongTien = exe.TongThanhTien(labMaPhieu.Text);
            numTienChietKhau.Value = TongTien * (numChietKhau.Value / 100);
            numThanhToan.Value = TongTien - numTienChietKhau.Value - numTienKM.Value;
        }
        private void treeHoaDon_AfterSelectionChange(object sender, HLVControl.Grid.Events.TreeListElementEventArgs e)
        {
            try
            {
                TreeListRow firstSelected = treeHoaDon.SelectedElements[0] as TreeListRow;
                int ID = int.Parse(firstSelected.Cells[2].Text);
                PRODUCT obj = exeMatHang.GetByID(ID);
                if (obj == null) return;
                labMaChiTiet.Text = obj.PrID.ToString();
            }
            catch
            {

            }
        }
        private void btnHuyPhieu_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Bạn có chắc muốn xóa phiếu nhập này không?", "Thông Báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                XoaPhieuTam(false);
            }
        }
        private void btnTaoPhieu_Click(object sender, EventArgs e)
        {
            if (labMaNCC.Text == "")
            {
                MessageBox.Show("Vui lòng chọn nhà cung cấp trước khi nhập mặt hàng!");
                return;
            }
            if (labMaKho.Text == "")
            {
                MessageBox.Show("Vui lòng chọn kho trước khi nhập mặt hàng!");
                return;
            }
            if (labMaPhieu.Text == "")
            {
                MessageBox.Show("Vui lòng chọn phieu!");
                return;
            }
           
            bool KQ = false;
            string MaPhieuTao = TaoMaPhieu(false);
            KQ = exe.XuLyNghiepVu(labMaPhieu.Text, int.Parse(labMaChiTiet.Text), int.Parse(labMaHang.Text), (int)numSLNhap.Value, (double)numDonGiaChon.Value, int.Parse(labMaNCC.Text), labMaKho.Text, (float)numChietKhau.Value, (double)numTienKM.Value, (double)numTienChi.Value, StaticVar.user.UserName, "Mới tạo", 1, txtGhiChu.Text, false,MaPhieuTao, "TaoPhieu");
            if (KQ)
            {
                LoadUI();
                MessageBox.Show("Tạo phiếu thành công");
            }
        }

        private void btnXoaHang_Click(object sender, EventArgs e)
        {
             XoaMatHang();
        }

    }
}
